package com.zhen.interceptor.service.impl;

import com.zhen.interceptor.service.ThreadService;
import com.zhen.interceptor.thread.MyApplyTask;
import com.zhen.interceptor.thread.MySumTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.*;

@Service
@Slf4j
public class ThreadServiceImpl implements ThreadService {
    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    ThreadPoolTaskExecutor executor;

    @Override
    public void apply() throws InterruptedException {
        Map<String, Object> params = new HashMap<>();
        params.put("name", "zhangsan");
        params.put("age", "22");
        // 创建一个线程执行一些业务逻辑
        executor.execute(new MyApplyTask(params, applicationContext.getBean(ThreadService.class)));
        Thread.sleep(1000L);
        // TODO 继续原来的业务逻辑
        log.info("apply方法继续执行，继续原来的业务逻辑");

    }

    @Override
    public void doApplyTask(Map<String, Object> params) {
        log.info("doApplyTask开始执行，入参是params:{}", params);
    }

    @Override
    public void sum() {
        List<Future<Integer>> resultList = new ArrayList<>();
        // 线程数量
        int threadNum = 10;
        // 有界队列
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(6);
        // 放弃拒绝的任务并抛出异常
        RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy();
        CountDownLatch downLatch = new CountDownLatch(threadNum);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(threadNum, threadNum, 6L, TimeUnit.SECONDS, queue, handler);

        for (int i = 0; i < 10; i++) {
            MySumTask task = new MySumTask(i * 100 + 1, (i + 1) * 100);
            Future<Integer> result = poolExecutor.submit(task);
            downLatch.countDown();
            resultList.add(result);
        }
        //
        poolExecutor.shutdown();
        // 等待所有线程执行完毕
        try {
            downLatch.await();
            log.info("所有子线程执行完毕");
        } catch (InterruptedException e) {
            log.error("线程执行异常", e);
        }
        // 结果解析
        int total = analysisResult(resultList);
        log.info("最终返回结果是{}", total);
    }

    private int analysisResult(List<Future<Integer>> resultList) {
        int total = 0;
        for (int i = 0; i < resultList.size(); i++) {
            Future<Integer> result = resultList.get(i);
            Integer sum = null;
            try {
                sum = result.get();
                total += sum;
            } catch (Exception e) {
                log.error("结果解析异常", e);
            }
        }
        return total;
    }

    @Override
    public void sum2() {
        List<Future<Integer>> resultList = new ArrayList<>();
        // 线程数量
        int threadNum = 5;
        // 有界队列
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(6);
        // 放弃拒绝的任务并抛出异常
        RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy();
        CountDownLatch downLatch = new CountDownLatch(threadNum);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(threadNum, threadNum, 6L, TimeUnit.SECONDS, queue, handler);

        for (int i = 0; i < 10; i++) {
            int startNum = i * 100 + 1;
            int endNum = (i + 1) * 100;
            Future<Integer> result = poolExecutor.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    int sum = 0;
                    for (int i = startNum; i <= endNum; i++) {
                        sum += i;
                    }
                    String threadName = Thread.currentThread().getName();
                    int sleep = new Random().nextInt(1000);
                    Thread.sleep(sleep);
                    log.info("线程{}等待时间是{}，执行的是从{}到{}，执行的结果是{}", threadName, sleep, startNum, endNum, sum);
                    downLatch.countDown();
                    return sum;
                }
            });
            resultList.add(result);
        }
        //
        poolExecutor.shutdown();
        // 等待所有线程执行完毕
        try {
            downLatch.await();
            log.info("所有子线程执行完毕");
        } catch (InterruptedException e) {
            log.error("线程执行异常", e);
        }
        // 结果解析
        int total = analysisResult(resultList);
        log.info("最终返回结果是{}", total);
    }
}
